//
//  PywAppleReceipt.m
//  PywSdk
//
//  Created by Jade on 16/7/27.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywAppleReceipt.h"

#define passportPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"AppleReceipt"]

@implementation PywAppleReceipt
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.orderNum forKey:@"orderNum"];
    [aCoder encodeObject:self.receipt forKey:@"receipt"];
    [aCoder encodeObject:self.productId forKey:@"productId"];
    [aCoder encodeObject:self.account forKey:@"account"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self.orderNum = [aDecoder decodeObjectForKey:@"orderNum"];
    self.receipt = [aDecoder decodeObjectForKey:@"receipt"];
    self.productId = [aDecoder decodeObjectForKey:@"productId"];
    self.account = [aDecoder decodeObjectForKey:@"account"];
    return self;
}

/**
 *  保存单个票据
 */
+ (void)saveReceipt:(PywAppleReceipt *)receipt {
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:passportPath];
    NSMutableArray *receipts = [NSMutableArray arrayWithArray:array];
    [receipts addObject:receipt];
    
    [NSKeyedArchiver archiveRootObject:receipts toFile:passportPath];
}
/**
 *  保存票据数组
 */
+ (void)saveReceiptList:(NSArray *)array {
    [NSKeyedArchiver archiveRootObject:array toFile:passportPath];
}
/**
 *  返回票据数组
 */
+ (NSArray *)receipts {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:passportPath];
}

/**
 *  根据订单号返回票据
 */
+ (void)removeReceipt:(NSString *)orderNum
{
    if (orderNum.length == 0) {
        return;
    }
    @try {
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:passportPath];
        NSMutableArray *receipts = [NSMutableArray arrayWithArray:array];
        
        for (NSInteger i = 0; i < receipts.count; i ++) {
            PywAppleReceipt *receipt = [receipts objectAtIndex:i];
            if ([receipt.orderNum isEqualToString:orderNum]) {
                [receipts removeObjectAtIndex:i];
            }
        }
        [NSKeyedArchiver archiveRootObject:receipts toFile:passportPath];
    } @catch (NSException *exception) {
        PLog(@"删除票据失败");
    } @finally {
        
    }
    
}

@end
